// 变异观察者模块 - 监听DOM变化
import { logDOMInfo, logRemoval } from './logger.js';

// 移除DOM元素
function removeDOMs(selector) {
  const elements = document.querySelectorAll(selector);
  elements.forEach(function (element) {
    // 记录通过选择器查询移除的DOM元素
    logDOMInfo(element, 'MutationObserver监测', selector);
    element.remove();
  });
  if (elements.length > 0) {
    logRemoval(selector, elements.length);
  }
}

// 设置dom观察者
export function setupMutationObserver(selectors) {
  const observer = new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.addedNodes.length > 0) {
        for (const selector of selectors) {
          removeDOMs(selector);
        }
        break;
      }
    }
  });

  // 配置观察器选项
  const config = {
    childList: true,
    subtree: true,
    attributes: false,
    characterData: false
  };

  // 开始观察整个document
  observer.observe(document.documentElement, config);

  // 页面卸载时清理
  window.addEventListener('unload', () => {
    if (observer) {
      observer.disconnect();
    }
  });
}